package com.itheima.easyexceldemo.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.itheima.easyexceldemo.annotation.AutoAnnotation;
import com.itheima.easyexceldemo.enumeration.OperationType;
import com.itheima.easyexceldemo.mapper.ExcelMapper;
import com.itheima.easyexceldemo.pojo.Dept;
import com.itheima.easyexceldemo.service.ExcelService;
import com.itheima.easyexceldemo.utils.DemoDataListener;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * TODO
 *
 * @Author mr.luo
 * @Date 13 4月 2025 01:07
 */

@Service
@Slf4j
public class ExcelServiceImpl implements ExcelService {
    @Autowired
    private ExcelMapper excelMapper;

    /**
     * easyexcel导出部门数据
     */
    @Override
    public void exportDept(HttpServletResponse response) throws IOException {
        List<Dept> depts = excelMapper.exportDept();
        log.info("导出部门数据");

      //导出XLSX文件，设置响应头信息，编码 UTF-8
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//        response.setCharacterEncoding("UTF-8");
        EasyExcel.write(
                        response.getOutputStream(), Dept.class
                )
                .head(Dept.class)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet("部门数据")
                .doWrite(depts);
    }

    /**
     * 导入部门数据
     *
     * @param file
     */
    @AutoAnnotation(value = OperationType.insert)
    @Override
    public void importDept(MultipartFile file) throws IOException {
        InputStream is = file.getInputStream();
        EasyExcel.read(
                        is, Dept.class, new DemoDataListener(excelMapper)
                )
                .sheet(0)// 读取第一个sheet
                .headRowNumber(2)// 设置标题行数
                .doRead();
    }
}
